<?php

require_once(BASE_ROOT_PATH.'/weixin/framework/libraries/wechat.class.php');
require_once(BASE_ROOT_PATH.'/weixin/language/zh_cn/wx_msg.php');

class wxSdk extends Wechat
{
    private $path;
    private $authorised;//授权方式
    public $templateMsgData = array();//模板消息体

    public function __construct()
    {
        $options['token'] = "f8sSRmR5f5rrVr5CRtIvBvikHsvKHDPR";
        $options['appid'] = "wxc68b4e72af13c1cf";
        $options['appsecret'] = "d9c3554d06110ad3920422e90cbd1e09";
        $options['logcallback'] = "recordLog";
        if (empty($options['authorised']) || !in_array($options['authorised'], array('snsapi_userinfo', 'snsapi_base'))) {
            $this->authorised = 'snsapi_base';
        } else {
            $this->authorised = $options['authorised'];
        }
        parent::__construct($options);
        $this->path = BASE_PATH . '/data/';
    }


    public function test()
    {
        //$this->setCache('asttttt','444444444',1500);
        //return $this->getCache('asttttt');
        //$this->removeCache('asttttt');
        //unlink('D:/phpStudy/WWW/shopnc/weixin/data/asttttt.json');
    }


    /**
     * webAuthGetCode
     * 微信网页授权第一步 ，获取code
     */
    public function webAuthGetCode()
    {
        global $config;
        $requestUrl = $config['site_url'] . "{$_SERVER['REQUEST_URI']}";//SITE_URL . $_SERVER['REQUEST_URI'];
        $oauthUrl = $this->getOauthRedirect($requestUrl, 'oauth', $this->authorised);
        header('Location:' . $oauthUrl);
        exit;
    }


    /**
     * log overwrite
     * @see Wechat::log()
     */
    protected function log($log)
    {
        if ($this->debug) {
            if (function_exists($this->logcallback)) {
                if (is_array($log)) $log = serialize($log);
                return call_user_func($this->logcallback, $log);
            }
            return false;
//            elseif (class_exists('Log')) {
//                Log::write('wechat：' . $log, Log::DEBUG);
//                return true;
//            }
        }
        return false;
    }

    /**
     * 重载设置缓存
     * @param string $cachename
     * @param mixed $value
     * @param int $expired
     * @return boolean
     */
    protected function setCache($cachename, $value, $expired)
    {
        $data['jsapi_ticket'] = $value;
        $data['expire_time'] = time() + intval($expired);
        file_put_contents("{$this->path}$cachename.json", json_encode($data));
        return true;
    }

    /**
     * 重载获取缓存
     * @param string $cachename
     * @return mixed
     */
    protected function getCache($cachename)
    {
        if (file_exists("{$this->path}$cachename.json")) {
            $data = json_decode(file_get_contents("{$this->path}$cachename.json"));
            if ($data->expire_time < time()) {
                return false;
            } else {
                return $data->jsapi_ticket;
            }
        } else {
            return false;
        }
    }

    /**
     * 重载清除缓存
     * @param string $cachename
     * @return boolean
     */
    protected function removeCache($cachename)
    {
        if (file_exists("{$this->path}$cachename.json")) {
            if (unlink("{$this->path}$cachename.json")) return true;
            return false;
        }
        return true;
    }

    /**
     * recordLog
     * 记录日志
     * $log string
     */
    private function recordLog($log = '')
    {
        $now = date('Y-m-d H:i:s', time());
        $log_file = BASE_DATA_PATH . '/log/' . date('Ymd', TIMESTAMP) . '.log';
        $content = "[{$now}]: {$log}\r\n";
        if (file_put_contents($log_file, $content, FILE_APPEND)) return true;
        return false;
    }


    /**
     * Touser
     * 组装模板消息体
     * 发送者
     * @param $param
     * @return $this
     */
    public function Touser($param)
    {
        $member_model = Model('member');
        $map['member_id'] = $param['member_id'];
        $member_info = $member_model->getMemberInfo($map);
        if ($member_info['member_wxopenid']) {
            $this->templateMsgData['touser'] = $member_info['member_wxopenid'];
        } else {
            $this->templateMsgData['touser'] = 'null';
        }
        return $this;
    }

    /**
     * TemplateId
     * 组装模板消息体
     * 模板id
     * @param int $type
     * $type = array(
        1=>'新订单通知',
        2=>'发货通知（发给买家--货到付款）',
        3=>'发货通知',
     * )
     * @return $this
     */
    public function TemplateId($type = 1)
    {
        $template_id = '';
        switch ($type) {
            case 1:
                //新订单通知
                $template_id = 'CtNUFmnSnHBB3n11I-VM3gDZ7JQPUpWcXZ44-_DRFWo';
                break;
            case 2:
                //发货通知（发给买家--货到付款）
                $template_id = '0ppwBjG_6mLPRplHZQcpuHtNHx8Xq4KPNuEfRBFeBWs';
                break;
            case 3:
                //发货通知
                $template_id = 'yyZbNUN2JD_vRfiRXnw4kEpFvZn_et9wTq6DmhEUm-E';
                break;
            case 4:
                //返现通知
                $template_id = 'Ga2X_va_p5q3Ex4GCMyPSBuw9WyZEQZrWsBRevPreqE ';
                break;
        }
        $this->templateMsgData['template_id'] = $template_id;
        return $this;
    }

    /**
     * TemplateUrl
     * 组装模板消息体
     * 消息链接url
     * @param int $status 1 == 开启url
     * @param $url
     * @return $this
     */
    public function TemplateUrl($status = 1, $url)
    {
        if ($status == 1 && !empty($url)) {
            $this->templateMsgData['url'] = $url;
        } else {
            $this->templateMsgData['url'] = '';
        }
        return $this;
    }

    /**
     * setTemplateTopColor
     * 组装模板消息体
     * 头部颜色
     * @param string $color 颜色值
     * @return $this
     */
    public function setTemplateTopColor($color = '#fff')
    {
        $this->templateMsgData['topcolor'] = $color;
        return $this;
    }

    /**
     * setTemplateData
     * 组装模板消息体
     * 消息内容
     * @param int $type 模板类型对应数据体格式
     * $type = array(
            1=>'新订单通知买家',
            2=>'新订单通知买家货到付款',
            3=>'新订单通知卖家',
            4=>'新订单通知卖家(货到付款)',
            5=>'发货通知（发给买家--货到付款）',
            6=>'发货通知，发给买家',
            7=>'发货通知，发给卖家',
     * )
     * @param array $param
     * @return $this
     */
    public function setTemplateData($type = 1, $param = array())
    {
        global $lang;
        switch ($type) {
            case 1://新订单通知买家
                $data = array(
                    'first' => array(
                        'value' => $lang['wx_order_new'],
                        'color' => '#173177'
                    ),
                    //订单名称
                    'keyword1' => array(
                        'value' => $param['goods_name'],
                        'color' => '#173177'
                    ),
                    //订单价格
                    'keyword2' => array(
                        'value' => $param['goods_pay_price'].'(抵扣红包：'.$param['profit'].')',
                        'color' => '#173177'
                    ),
                    //订单数量
                    'keyword3' => array(
                        'value' => $param['goods_num'],
                        'color' => '#173177'
                    ),
                    //订单类型
                    'keyword4' => array(
                        'value' => $lang['wx_order_state_pay_way_online'],
                        'color' => '#173177'
                    ),
                    //订单状态
                    'keyword5' => array(
                        'value' => $lang['wx_order_state_pay'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => $lang['wx_order_buyer_remark_new'],
                        'color' => '#173177'
                    )
                );
                break;
            case 2://新订单通知买家货到付款
                $data = array(
                    'first' => array(
                        'value' => $lang['wx_order_new'],
                        'color' => '#173177'
                    ),
                    //订单名称
                    'keyword1' => array(
                        'value' => $param['goods_name'],
                        'color' => '#173177'
                    ),
                    //订单价格
                    'keyword2' => array(
                        'value' => $param['goods_pay_price'].'(抵扣红包：'.$param['profit'].')',
                        'color' => '#173177'
                    ),
                    //订单数量
                    'keyword3' => array(
                        'value' => $param['goods_num'],
                        'color' => '#173177'
                    ),
                    //订单类型
                    'keyword4' => array(
                        'value' => $lang['wx_order_state_pay_way_offline'],
                        'color' => '#173177'
                    ),
                    //订单状态
                    'keyword5' => array(
                        'value' => $lang['wx_order_state_pay'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => $lang['wx_order_buyer_remark_new'],
                        'color' => '#173177'
                    )
                );
                break;
            case 3://新订单通知卖家
                $data = array(
                    'first' => array(
                        'value' => $lang['wx_order_new'],
                        'color' => '#173177'
                    ),
                    //订单名称
                    'keyword1' => array(
                        'value' => $param['goods_name'],
                        'color' => '#173177'
                    ),
                    //订单价格
                    'keyword2' => array(
                        'value' => $param['goods_pay_price'].'(抵扣红包：'.$param['profit'].')',
                        'color' => '#173177'
                    ),
                    //订单数量
                    'keyword3' => array(
                        'value' => $param['goods_num'],
                        'color' => '#173177'
                    ),
                    //订单类型
                    'keyword4' => array(
                        'value' => $lang['wx_order_state_pay_way_online'],
                        'color' => '#173177'
                    ),
                    //订单状态
                    'keyword5' => array(
                        'value' => $lang['wx_order_state_pay'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => $lang['wx_order_seller_remark_new'],
                        'color' => '#173177'
                    )
                );
                break;
            case 4://新订单通知卖家(货到付款)
                $data = array(
                    'first' => array(
                        'value' => $lang['wx_order_new'],
                        'color' => '#173177'
                    ),
                    //订单名称
                    'keyword1' => array(
                        'value' => $param['goods_name'],
                        'color' => '#173177'
                    ),
                    //订单价格
                    'keyword2' => array(
                        'value' => $param['goods_pay_price'].'(抵扣红包：'.$param['profit'].')',
                        'color' => '#173177'
                    ),
                    //订单数量
                    'keyword3' => array(
                        'value' => $param['goods_num'],
                        'color' => '#173177'
                    ),
                    //订单类型
                    'keyword4' => array(
                        'value' => $lang['wx_order_state_pay_way_offline'],
                        'color' => '#173177'
                    ),
                    //订单状态
                    'keyword5' => array(
                        'value' => $lang['wx_order_state_pay'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => $lang['wx_order_seller_remark_new'],
                        'color' => '#173177'
                    )
                );
                break;
            case 5://发货通知（发给买家--货到付款）
                $reciver_info = $param['reciver_info'];
                $data = array(
                    'first' => array(
                        'value' => $lang['wx_order_first_send_buyer_offline'],
                        'color' => '#173177'
                    ),
                    //收货人姓名
                    'keyword1' => array(
                        'value' => $param['reciver_name'],
                        'color' => '#173177'
                    ),
                    //联系方式
                    'keyword2' => array(
                        'value' => $reciver_info['phone'],
                        'color' => '#173177'
                    ),
                    //收货地址
                    'keyword3' => array(
                        'value' => $reciver_info['address'],
                        'color' => '#173177'
                    ),
                    //货款
                    'keyword4' => array(
                        'value' => $param['order_amount']. ' 元',
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => $lang['wx_order_buyer_remark_offline'],
                        'color' => '#173177'
                    )
                );
                break;
            case 6://发货通知，发给买家
                $reciver_info = $param['reciver_info'];
                $data = array(
                    'first' => array(
                        'value' => $lang['wx_order_first_send_buyer'],
                        'color' => '#173177'
                    ),
                    //订单金额
                    'orderProductPrice' => array(
                        'value' => $param['order_amount'] . ' 元',
                        'color' => '#173177'
                    ),
                    //商品详情
                    'orderProductName' => array(
                        'value' => $param['order_goods_info'],//商品名称（件数）
                        'color' => '#173177'
                    ),
                    //收货信息
                    'orderAddress' => array(
                        'value' => $param['reciver_name'].' '.$reciver_info['phone'].' '. $reciver_info['address'],
                        'color' => '#173177'
                    ),
                    //订单编号
                    'orderName' => array(
                        'value' => $param['order_sn'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => $lang['wx_order_buyer_remark_online'],
                        'color' => '#173177'
                    )
                );
                break;
            case 7://发货通知，发给卖家
                $reciver_info = $param['reciver_info'];
                $data = array(
                    'first' => array(
                        'value' => $lang['wx_order_first_send_seller'],
                        'color' => '#173177'
                    ),
                    //订单金额
                    'orderProductPrice' => array(
                        'value' => $param['order_amount'] . ' 元',
                        'color' => '#173177'
                    ),
                    //商品详情
                    'orderProductName' => array(
                        'value' => $param['order_goods_info'],
                        'color' => '#173177'
                    ),
                    //收货信息
                    'orderAddress' => array(
                        'value' => $param['reciver_name'].' '.$reciver_info['phone'].' '. $reciver_info['address'],
                        'color' => '#173177'
                    ),
                    //订单编号
                    'orderName' => array(
                        'value' => $param['order_sn'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => $lang['wx_order_seller_remark_send'],
                        'color' => '#173177'
                    )
                );
                break;
            case 8://返现通知
                $data = array(
                    'first' => array(
                        'value' => $lang['wx_order_first_send_cash_back'],
                        'color' => '#173177'
                    ),
                    //订单号
                    'keyword1' => array(
                        'value' => $param['order_sn'],
                        'color' => '#173177'
                    ),
                    //订单金额
                    'keyword2' => array(
                        'value' => $param['order_amount'],
                        'color' => '#173177'
                    ),
                    //返现金额
                    'keyword3' => array(
                        'value' => $param['brokerage'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => $lang['wx_order_seller_remark_cash_back'],
                        'color' => '#173177'
                    )
                );
                break;
        }
        $this->templateMsgData['data'] = $data;
        return $this;

    }

    /**
     * sendTemplateMessage
     * 发送模板消息
     */
    public function sendTemplateMessage($data = array())
    {
        //重新映射数组
        $data = array(
            'touser' => $this->templateMsgData['touser'],
            'template_id' => $this->templateMsgData['template_id'],
            'url' => $this->templateMsgData['url'],
            'topcolor' => $this->templateMsgData['topcolor'],
            'data' => $this->templateMsgData['data']
        );
        parent::sendTemplateMessage($data);
    }

}